import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/decorator'
import { Context } from 'egg'

import { BaseController } from './base'
import { CODE } from '../constants/code'
import { SmsService } from '../service/sms'

interface SMS {
  phone: string,
  code?: string
}
@Provide()
@Controller('/api/sms')
export class SmsController extends BaseController {

  @Inject()
  ctx: Context

  @Inject()
  smsService: SmsService

  @Post('/')
  async sendSms(@Body(ALL) sms: SMS) {
    if (
      typeof sms.phone !== 'string' ||
      !/^[0-9]*$/.test(sms.phone)
    ) {
      return this.notOk(CODE.SMS_PHONE_INVALID)
    }

    try {
      const code = await this.smsService.send(sms.phone)

      if (code) {
        return this.ok()
      }

      return this.notOk(CODE.SMS_LIMIT)
    } catch (err) {
      return this.notOk(CODE.FAIL)
    }
  }

  @Post('/validate')
  async validateSms(@Body(ALL) sms: SMS) {
    if (
      typeof sms.phone !== 'string' ||
      !/^[0-9]*$/.test(sms.phone)
    ) {
      return this.notOk(CODE.SMS_PHONE_INVALID)
    }

    if (!sms.code) {
      return this.notOk(CODE.SMS_CODE_INVALID)
    }

    const isValid = await this.smsService.validate(sms.phone, sms.code)

    if (isValid) {
      return this.ok()
    }

    return this.notOk(CODE.SMS_CODE_INCORRECT)
  }
}
